package com.galaxy.device.controller;

import com.galaxy.common.core.domain.R;
import com.galaxy.device.domain.DeviceStatus;
import com.galaxy.device.domain.convert.DeviceStatusConvert;
import com.galaxy.device.domain.vo.DeviceStatusVo;
import com.galaxy.device.service.InfluxDBService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.util.List;
import java.util.TimeZone;

/**
 * 设备状态监控控制器
 */
@Tag(name = "设备状态监控管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/monitor")
public class DeviceStatusMonitorController {

    private final InfluxDBService influxDBService;

    /**
     * 获取设备实时状态
     */
    @Operation(summary = "获取设备实时状态")
    @GetMapping("/status/{deviceNo}")
    public R<List<DeviceStatusVo>> getDeviceStatus(
        @PathVariable("deviceNo") String deviceNo,
        @RequestParam(value = "start", required = false) String startStr,
        @RequestParam(value = "end", required = false) String endStr) {

        // 如果没有指定时间范围，默认查询最近1小时的数据
        Instant start;
        Instant end;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));

        try {
            if (startStr != null) {
                start = sdf.parse(startStr).toInstant();
            } else {
                start = Instant.now().minusSeconds(3600); // 1小时前
            }

            if (endStr != null) {
                end = sdf.parse(endStr).toInstant();
            } else {
                end = Instant.now();
            }
        } catch (ParseException e) {
            // 处理解析异常
            return R.fail("时间格式错误");
        }

        List<DeviceStatus> statusList = influxDBService.queryDeviceStatusByConditions(deviceNo, start, end);
        return R.ok(DeviceStatusConvert.INSTANCE.convertVoList(statusList));
    }

    /**
     * 获取设备历史状态
     */
    @Operation(summary = "获取设备历史状态")
    @GetMapping("/history/{deviceNo}")
    public R<List<DeviceStatusVo>> getDeviceHistory(
        @PathVariable("deviceNo") String deviceNo,
        @RequestParam("start") Instant start,
        @RequestParam("end") Instant end) {
        List<DeviceStatus> statusList = influxDBService.queryDeviceStatusByConditions(deviceNo, start, end);
        return R.ok(DeviceStatusConvert.INSTANCE.convertVoList(statusList));
    }
}
